<?php
/**
 * User: Tegic
 * Date: 2018/6/13
 * Time: 09:47
 */
 
namespace app\workerman;

use GatewayWorker\Lib\Gateway;
use app\common\model\User;

use Workerman\Worker;
 
class Events
{
    
    protected $db = null;
    
    public static function onWorkerStart($businessWorker)
    {

    }
 
    public static function onConnect($client_id)
    {
        Gateway::sendToClient($client_id, json_encode(['text'=>'连接成功', 'action'=>'connect'], true));
    }
 
    public static function onWebSocketConnect($client_id, $data)
    {
    }
 
    public static function onMessage($client_id, $message)
    {


        $message = json_decode($message, true);
        #登录
        if(isset($message['uid']) && $message['action'] == 'login') {
            Gateway::bindUid($client_id, $message["uid"]);
            $return_msg = ['text'=>'hello 登录成功', 'action'=>'connect'];
            // dump(json_encode($return_msg, true));
            Gateway::sendToClient($client_id, json_encode($return_msg, true));

        }
        #发送消息
        if($message['action'] == 'message') {
            $otherid = $message['user_id'];
            $return_msg = ['text'=>'sorry 该用户不在线', 'action'=>'error'];
            if(!GateWay::isUidOnline($otherid)) {
                Gateway::sendToClient($client_id, json_encode($return_msg, true));
            }
            
            Gateway::sendToUid($otherid, json_encode(['action'=>'message', 'text'=>$message['text']], true));
        }
        
        
        
        // Gateway::sendToClient($client_id, 'jiangwnagshengzuishuai');
        // Gateway::sendToClient($client_id, 'jiangwnagshengzuishuai');
        // Gateway::sendToAll('jiangwnagshengzuishuai');
    }
 
    public static function onClose($client_id)
    {   
        #通过client_id获取uid
        $uid = GateWay::getUidByClientId($client_id);
        #查看用户名
        $User = new User();
        $username = $User->findUserById($uid);
        dump($username['username']);
        $message = json_encode(['action'=>'login_out', 'text'=>"client[".$username['username']."] logout\n"], true);
        #判断管理员在线
        if(GateWay::isUidOnline('1')) {
            GateWay::sendToUid("1", $message);
        }
        #接触绑定
        Gateway::unbindUid($client_id, $uid);
        GateWay::sendToAll($message);

    }
}
